using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Net.Configuration;

public partial class SearchBooks : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (null != Membership.GetUser())
            {
                if (Roles.IsUserInRole(Membership.GetUser(true).UserName, "user"))
                {
                    ((GridView)this.LoginViewUser.FindControl("bookListView")).Visible = false;
                    ((DetailsView)this.LoginViewUser.FindControl("bookDetailsView")).Visible = false;
                    ((Label)this.LoginViewUser.FindControl("detailsLabel")).Visible = false;
                    ((Label)this.LoginViewUser.FindControl("detailsComplete")).Visible = false;
                }

                if (Roles.IsUserInRole(Membership.GetUser(true).UserName, "admin"))
                {
                    ((GridView)this.LoginViewAdmin.FindControl("bookListViewAdmin")).Visible = false;
                    ((DetailsView)this.LoginViewAdmin.FindControl("bookDetailsViewAdmin")).Visible = false;
                    ((Label)this.LoginViewAdmin.FindControl("detailsLabel")).Visible = false;
                    ((Label)this.LoginViewAdmin.FindControl("detailsComplete")).Visible = false;
                }
            }
        }
    }

    /* User Related Methods */

    protected void searchButton_Click(object sender, EventArgs e)
    {
        string searchKey = ((TextBox)this.LoginViewUser.FindControl("searchKey")).Text;
        ((SqlDataSource)this.LoginViewUser.FindControl("SqlDataSource1")).SelectCommand =
            "SELECT bookid, title, publisher, substring(title,0,25) AS shortTitle, substring(author,0,10) as shortAuthor, author, substring(publisher,0,15) AS shortPublisher, language, number, requested FROM [books] WHERE [bookid] LIKE '%" + searchKey + "%' OR [title] LIKE '%" + searchKey + "%' OR [author] LIKE '%" + searchKey + "%' OR [publisher] LIKE '%" + searchKey + "%' OR [language] LIKE '%" + searchKey + "%' ORDER BY [author], [title], [publisher]";
        ((GridView)this.LoginViewUser.FindControl("bookListView")).DataBind();
        ((GridView)this.LoginViewUser.FindControl("bookListView")).Visible = true;

    }

    protected void bookListView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            int index = Convert.ToInt32(e.CommandArgument); // Get the index of the clicked row
            showBookDetails(index);
        }
    }

    private void showBookDetails(int rowIndex)
    {
        DetailsView bookDetailsView = ((DetailsView)this.LoginViewUser.FindControl("bookDetailsView"));
        GridView bookListView = ((GridView)this.LoginViewUser.FindControl("bookListView"));
        string primaryKey = (string)bookListView.DataKeys[rowIndex].Value;
        ((SqlDataSource)this.LoginViewUser.FindControl("SqlDataSource2")).SelectCommand = 
            "SELECT * FROM [books] WHERE bookid = '" + primaryKey + "'";
        //((Label)this.LoginViewUser.FindControl("detailsLabel")).DataBind();
        bookListView.DataBind();

        bookDetailsView.Visible = true;
        ((Label)this.LoginViewUser.FindControl("detailsLabel")).Visible = true;
    }

    protected void bookDetailsView_ItemCommand(object sender, DetailsViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Request"))
            RequestBook();
    }

    private void RequestBook()
    {
        GridView bookListView = ((GridView)this.LoginViewUser.FindControl("bookListView"));
        DetailsView bookDetailsView = ((DetailsView)this.LoginViewUser.FindControl("bookDetailsView"));

        if (int.Parse(bookDetailsView.Rows[5].Cells[1].Text) - int.Parse(bookDetailsView.Rows[6].Cells[1].Text) <= 0)
        {
            Response.Write("not available!");
        }
        else
        {
            /* Grab bookid from the DetailsView */
            string primaryKey = bookDetailsView.Rows[0].Cells[1].Text;

            SqlConnection connection =
                new SqlConnection(ConfigurationManager.ConnectionStrings["sylib"].ConnectionString);
            connection.Open();

            /* Add 1 to the requested count */
            string sCommand = "UPDATE [books] SET [requested] = [requested]+1 WHERE [bookid] = '" + primaryKey + "'";
            SqlCommand cmd = new SqlCommand(sCommand, connection);
            cmd.ExecuteNonQuery();
            bookDetailsView.DataBind();

            /* Add username to the requests table */
            sCommand = "INSERT INTO requests(username,requestedbookid) VALUES('" + User.Identity.Name + "','" + 
                primaryKey + "')";
            cmd = new SqlCommand(sCommand, connection);
            cmd.ExecuteNonQuery();

            /* grab book and transaction information */
            sCommand = "SELECT [requestid], [title] FROM [requests], [books] WHERE [bookid] = '" + primaryKey + 
                "' AND [requestedbookid] = '" + primaryKey + "' AND [username] = '" + User.Identity.Name + "'";
            cmd = new SqlCommand(sCommand, connection);
            SqlDataReader dataReader;
            dataReader = cmd.ExecuteReader();
            dataReader.Read();
            string transactionId = dataReader.GetInt32(0).ToString();
            string bookTitle = dataReader.GetString(1);

            connection.Close();

            /* Give the user their information on screen */
            ((Label)this.LoginViewUser.FindControl("detailsComplete")).Visible = true;
            ((Label)this.LoginViewUser.FindControl("detailsComplete")).Text = "Your request for the book <i>" +
                bookTitle + "</i> has been accepted, Request ID is " + transactionId + ".";
            ((Label)this.LoginViewUser.FindControl("detailsComplete")).Text += 
                "<br />A confirmation email will be sent " + Membership.GetUser().Email + 
                " and an administrator shortly.";

            /* Send an email to the user with thier information */
            SmtpClient mailClient = new SmtpClient();
            mailClient.Send
                (((SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp")).From, 
                Membership.GetUser().Email, "Sylib book request (" + transactionId + ")", 
                "You have requested the book [" + bookTitle +
                "] through the Sylib service.  Your Request ID for this transaction is " + transactionId +
                ".  You can review this transaction by visiting the My Books section of the Sylib service.  " +
                "This is an automatic message, replies will be sent directly to " + 
                ((SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp")).From + 
                ".\n\nIf this has been a mistake, please just ignore this message.");

            /* If the admin has it set, send the admin a notification too */
            connection = new SqlConnection(ConfigurationManager.ConnectionStrings["sylibSettings"].ConnectionString);
            connection.Open();
            sCommand = "SELECT [sendAdminEmail] FROM [settings] WHERE [id] = 0";
            cmd = new SqlCommand(sCommand, connection);
            int sendAdminEmail = (int)cmd.ExecuteScalar();
            if (1 == sendAdminEmail)
                mailClient.Send(((SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp")).From, 
                    ((SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp")).From, 
                    "Sylib book request (" + transactionId + ")", "User " + User.Identity.Name + 
                    " has requested the book [" + bookTitle + "] from you.  The Transaction ID is logged as " + 
                    transactionId + ".");
            connection.Close();
        }
    }

    /* Admin Related Methods */

    protected void searchButtonAdmin_Click(object sender, EventArgs e)
    {
        string searchKey = ((TextBox)this.LoginViewAdmin.FindControl("searchKey")).Text;
        ((SqlDataSource)this.LoginViewAdmin.FindControl("SqlDataSource1")).SelectCommand =
            "SELECT bookid, title, publisher, substring(title,0,25) AS shortTitle, substring(author,0,10) as shortAuthor, author, substring(publisher,0,15) AS shortPublisher, language, number, requested FROM [books] WHERE [bookid] LIKE '%" + searchKey + "%' OR [title] LIKE '%" + searchKey + "%' OR [author] LIKE '%" + searchKey + "%' OR [publisher] LIKE '%" + searchKey + "%' OR [language] LIKE '%" + searchKey + "%' ORDER BY [author], [title], [publisher]";
        ((GridView)this.LoginViewAdmin.FindControl("bookListViewAdmin")).DataBind();
        ((GridView)this.LoginViewAdmin.FindControl("bookListViewAdmin")).Visible = true;

    }

    protected void bookListViewAdmin_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            int index = Convert.ToInt32(e.CommandArgument); // Get the index of the clicked row
            showBookDetailsAdmin(index);
        }
    }

    private void showBookDetailsAdmin(int rowIndex)
    {
        /* When the user slects a row, we must update the details view immediatly */
        
        DetailsView bookDetailsViewAdmin = ((DetailsView)this.LoginViewAdmin.FindControl("bookDetailsViewAdmin"));
        GridView bookListViewAdmin = ((GridView)this.LoginViewAdmin.FindControl("bookListViewAdmin"));
        string primaryKey = (string)bookListViewAdmin.DataKeys[rowIndex].Value;
        ((SqlDataSource)this.LoginViewAdmin.FindControl("SqlDataSource2")).SelectCommand = 
            "SELECT * FROM [books] WHERE bookid = '" + primaryKey + "'";
        bookDetailsViewAdmin.DataBind();
        bookDetailsViewAdmin.Visible = true;
        ((Label)this.LoginViewAdmin.FindControl("detailsLabel")).Visible = true;
    }

    protected void bookDetailsViewAdmin_Load(object sender, EventArgs e)
    {
        /* We must also update the details view on load if a row has previously been selected 
         * This is so the details view is visible after pressing the "Edit" command 
         */

        //DetailsView bookDetailsViewAdmin = ((DetailsView)this.LoginViewAdmin.FindControl("bookDetailsViewAdmin"));
        //bookDetailsViewAdmin.DataBind();
        int rowIndex;
        GridView bookListViewAdmin = ((GridView)this.LoginViewAdmin.FindControl("bookListViewAdmin"));
        DetailsView bookDetailsViewAdmin = ((DetailsView)this.LoginViewAdmin.FindControl("bookDetailsViewAdmin"));

        rowIndex = bookListViewAdmin.SelectedIndex;
        if (rowIndex < 0)
            return;
        string primaryKey = (string)bookListViewAdmin.DataKeys[rowIndex].Value;
        ((TextBox)this.LoginViewAdmin.FindControl("hiddenSearchKey")).Text = primaryKey;
        
        return;
        /*
        int rowIndex;

        DetailsView bookDetailsViewAdmin = ((DetailsView)this.LoginViewAdmin.FindControl("bookDetailsViewAdmin"));
        GridView bookListViewAdmin = ((GridView)this.LoginViewAdmin.FindControl("bookListViewAdmin"));
        rowIndex = bookListViewAdmin.SelectedIndex;
        if (rowIndex < 0)
            return;

        string primaryKey = (string)bookListViewAdmin.DataKeys[rowIndex].Value;


        
        ((SqlDataSource)this.LoginViewAdmin.FindControl("SqlDataSource2")).SelectCommand =
            "SELECT * FROM [books] WHERE bookid = '" + primaryKey + "'";
        //((Label)this.LoginViewAdmin.FindControl("detailsLabel")).DataBind();
        
        ((TextBox)this.LoginViewAdmin.FindControl("searchKey")).Text = primaryKey;
        bookDetailsViewAdmin.DataBind();
        bookDetailsViewAdmin.Visible = true;
        ((Label)this.LoginViewAdmin.FindControl("detailsLabel")).Visible = true;
        */
    }

    protected void dosomething(object sender, EventArgs e)
    {
        return;
        
        DetailsView bookDetailsViewAdmin = ((DetailsView)this.LoginViewAdmin.FindControl("bookDetailsViewAdmin"));
        string theISBN = bookDetailsViewAdmin.Rows[0].Cells[1].Text;
        string newTitle = ((TextBox)bookDetailsViewAdmin.Rows[1].Cells[1].Controls[0]).Text;
        string newAuthor = ((TextBox)bookDetailsViewAdmin.Rows[2].Cells[1].Controls[0]).Text;
        string newPublisher = ((TextBox)bookDetailsViewAdmin.Rows[3].Cells[1].Controls[0]).Text;
        string newLanguage = ((TextBox)bookDetailsViewAdmin.Rows[4].Cells[1].Controls[0]).Text;
        string newNumber = ((TextBox)bookDetailsViewAdmin.Rows[5].Cells[1].Controls[0]).Text;
        string newRequested = ((TextBox)bookDetailsViewAdmin.Rows[6].Cells[1].Controls[0]).Text;

        SqlConnection connection =
            new SqlConnection(ConfigurationManager.ConnectionStrings["sylib"].ConnectionString);
        string sCommand = "UPDATE [books] SET [title] = '" + newTitle + "', [author] = '" + newAuthor + 
            "', [publisher] = '" + newPublisher + "', [language] = '" + newTitle + "', [requested] = " + 
            newRequested + ", [number] = " + newNumber + " WHERE [bookid] = '" + theISBN + "'";
        SqlCommand cmd = new SqlCommand(sCommand, connection);
        connection.Open();
        cmd.ExecuteNonQuery();
        connection.Close();

        //Response.Write(sCommand);
    }






    protected void Button2_Click(object sender, EventArgs e)
    {
        DetailsView bookDetailsViewAdmin = ((DetailsView)this.LoginViewAdmin.FindControl("bookDetailsViewAdmin"));
        bookDetailsViewAdmin.DataBind();
    }


}


